package com.book.controller;

import com.book.common.BaseController;
import com.book.common.CommonResult;
import com.book.common.NoRepeatSubmit;
import com.book.dto.AddressDto;
import com.book.dto.OrderDto;
import com.book.remote.AddressRemote;
import com.book.remote.BookApiRemote;
import com.book.remote.OrderRemote;
import com.book.remote.ShopCarRemote;
import com.book.vo.*;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @Author 李锦程
 * @Date 2021/4/25 8:20 下午
 * @Package com.book.controller
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {
    @Autowired
    private OrderRemote orderRemote;
    @Autowired
    private BookApiRemote uBookApi;
    @Autowired
    private AddressRemote addressRemote;
    @Autowired
    private ShopCarRemote shopCarRemote;


    @NoRepeatSubmit
    @RequestMapping("/saveOrder")
    @ResponseBody
    public CommonResult save(OrderDto dto, String bookCode, HttpSession session){
        log.info("OrderController.saveOrder#orderDto:{},bookCode:{}",dto,bookCode);
        String uCode = getUserCode();
        dto.setUCode(uCode);
        Boolean aBoolean = orderRemote.saveOrder(dto, bookCode);
        if (aBoolean){
            List<Integer> ids = (List<Integer>) session.getAttribute("shopCarId");
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(ids)){
                shopCarRemote.deleteShopCarDetail(ids);
                session.removeAttribute("shopCarId");
            }
            return CommonResult.successNoMsg();
        }
        return CommonResult.fail("下单失败");
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseVo list(HttpSession session){
        String uCode = getUserCode();
        List<OrderVo> orderVos = orderRemote.getListByUId(uCode);
        return ResponseVo.successResult(orderVos);
    }

    @RequestMapping("/index")
    public String index(HttpSession session, Model model){
        String uCode = getUserCode();
        List<OrderVo> orderVos = orderRemote.getListByUId(uCode);
        model.addAttribute("orderVos",orderVos);
        return "order/index.jsp";
    }

    @RequestMapping("/detail/{oid}")
    public String detail(@PathVariable("oid") Integer oid,Model model){
        OrderDetailVo orderDetailVo = orderRemote.getOrderById(oid);
        if (orderDetailVo == null){
            return "error-404.jsp";
        }
        model.addAttribute("oVO",orderDetailVo);
        return "order/detail.jsp";
    }

    @RequestMapping("/place/order/{bookCode}")
    public String okOrder(@PathVariable("bookCode") String bookCode,Integer num,Model model){
        /*UBookVo uBookDto = uBookApi.getBookByBookCode(bookCode);
        if (uBookDto != null){
            uBookDto.getUBookDto().setBookNum(1);
            model.addAttribute("book",uBookDto);
            model.addAttribute("totalPrice",uBookDto.getUBookDto().getBookPrice()*num);
            model.addAttribute("img",uBookDto.getImgUrl().get(0));
        }*/
        Map<String, List<OrderBookVo>> orderToPlace = orderRemote.getOrderToPlace(bookCode, num);
        /*String s = orderRemote.setOrderDetailCache(orderToPlace);
        model.addAttribute("orderNo",s);
        model.addAttribute("maps",orderToPlace);
        String userCode = getUserCode();
        List<AddressDto> list = addressRemote.getList(userCode);
        if (CollectionUtils.isEmpty(list)){
            model.addAttribute("addressNum",0);
        }else {
            model.addAttribute("addressNum",1);
        }
        model.addAttribute("addressList",list);*/
        getOrderPlaceModel(model,orderToPlace);
        return "order/placeOrder.jsp";
    }

    @RequestMapping("/car/place/order")
    @ResponseBody
    public ResponseVo carPlaceOrder(){

        return ResponseVo.errRest("下单失败");
    }

    @RequestMapping("/car/order/{carIds}")
    public String carToOrder(@PathVariable("carIds") String carIds,Model model,HttpSession session){
        String[] split = carIds.split(",");
        List<Integer> carIdList = Lists.newArrayList();
        for (int i = 0; i < split.length; i++) {
            carIdList.add(Integer.parseInt(split[i]));
        }
        Map<String, List<OrderBookVo>> shopDetailList = orderRemote.getShopDetailList(carIdList);
        getOrderPlaceModel(model,shopDetailList);
        session.setAttribute("shopCarId",carIdList);
        /*String s = orderRemote.setOrderDetailCache(shopDetailList);
        model.addAttribute("orderNo",s);
        model.addAttribute("maps",shopDetailList);
        String userCode = getUserCode();
        List<AddressDto> list = addressRemote.getList(userCode);
        if (CollectionUtils.isEmpty(list)){
            model.addAttribute("addressNum",0);
        }else {
            model.addAttribute("addressNum",1);
        }
        model.addAttribute("addressList",list);*/
        return "/order/placeOrder.jsp";
    }

    private void getOrderPlaceModel(Model model, Map<String,List<OrderBookVo>> map){
        String s = orderRemote.setOrderDetailCache(map);
        model.addAttribute("orderNo",s);
        model.addAttribute("maps",map);
        String userCode = getUserCode();
        List<AddressDto> list = addressRemote.getList(userCode);
        if (CollectionUtils.isEmpty(list)){
            model.addAttribute("addressNum",0);
        }else {
            model.addAttribute("addressNum",1);
        }
        model.addAttribute("addressList",list);
    }

    @RequestMapping("/mySellInfo")
    public String mySellInfo(Model model){
        Integer uId = getCurrentId();
        List<MySellerVo> mySellInfos = orderRemote.getMySellInfo(uId);
        log.info("OrderController mySellInfo :{}",mySellInfos);
        model.addAttribute("mysellInfoList",mySellInfos);
        return "/user/mySellInfo.jsp";
    }

    @RequestMapping("/cancel/{id}")
    public String cancel(@PathVariable("id") Integer id){
        Boolean aBoolean=orderRemote.updateOrderStatus(id,2);
        return "redirect:/order/index";
    }
    @RequestMapping("/ok/{id}")
    public String ok(@PathVariable("id") Integer id){
        Boolean aBoolean=orderRemote.updateOrderStatus(id,1);
        return "redirect:/order/index";
    }

    @RequestMapping("/search")
    @ResponseBody
    public ResponseVo search(String text,Integer status){
        try {
            String uCode = getUserCode();
            if (StringUtils.isEmpty(text)  && status == null){
                List<OrderVo> orderVos = orderRemote.getListByUId(uCode);
                return ResponseVo.successResult(orderVos);
            }
            List<OrderVo> voList = orderRemote.searchByNameOrStatus(uCode,text,status);
            return ResponseVo.successResult(voList);
        }catch (Exception e){
            log.error("OrderController seatch order error text:{},status:{}",text,status,e);
            return ResponseVo.errRest("查找失败");
        }
    }



}
